package zy.service.batch.prepay.impl;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import zy.dao.approve.ApproveRecordDAO;
import zy.dao.batch.client.ClientDAO;
import zy.dao.batch.dealings.BatchDealingsDAO;
import zy.dao.batch.prepay.BatchPrepayDAO;
import zy.dao.money.bank.BankDAO;
import zy.dao.money.bank.BankRunDAO;
import zy.entity.PageData;
import zy.entity.PageInfo;
import zy.entity.approve.T_Approve_Record;
import zy.entity.batch.client.T_Batch_Client;
import zy.entity.batch.dealings.T_Batch_Dealings;
import zy.entity.batch.prepay.T_Batch_Prepay;
import zy.entity.money.bank.T_Money_Bank;
import zy.entity.money.bank.T_Money_BankRun;
import zy.entity.sys.user.T_Sys_User;
import zy.service.batch.prepay.BatchPrepayService;
import zy.util.CommonUtil;
import zy.util.DateUtil;
import zy.util.StringUtil;

@Service
public class BatchPrepayServiceImpl implements BatchPrepayService{
	@Resource
	private BatchPrepayDAO batchPrepayDAO;
	@Resource
	private ApproveRecordDAO approveRecordDAO;
	@Resource
	private BatchDealingsDAO batchDealingsDAO;
	@Resource
	private ClientDAO clientDAO;
	@Resource
	private BankDAO bankDAO;
	@Resource
	private BankRunDAO bankRunDAO;
	
	@Override
	public PageData<T_Batch_Prepay> page(Map<String, Object> params) {
		Integer pageSize = (Integer)params.get(CommonUtil.PAGESIZE);
		Integer pageIndex = (Integer)params.get(CommonUtil.PAGEINDEX);
		
		Integer totalCount = batchPrepayDAO.count(params);
		PageInfo pageInfo = new PageInfo(totalCount, pageSize, pageIndex);
		params.put(CommonUtil.START, (pageIndex-1)*pageSize);
		params.put(CommonUtil.END, pageSize);
		
		List<T_Batch_Prepay> list = batchPrepayDAO.list(params);
		PageData<T_Batch_Prepay> pageData = new PageData<T_Batch_Prepay>();
		pageData.setPageInfo(pageInfo);
		pageData.setList(list);
		return pageData;
	}
	
	@Override
	public T_Batch_Prepay load(Integer pp_id) {
		T_Batch_Prepay prepay = batchPrepayDAO.load(pp_id);
		if(prepay != null){
			T_Approve_Record approve_Record = approveRecordDAO.load(prepay.getPp_number(), prepay.getCompanyid());
			if(approve_Record != null){
				prepay.setAr_describe(approve_Record.getAr_describe());
			}
		}
		return prepay;
	}
	
	@Override
	public T_Batch_Prepay load(String number,Integer companyid) {
		return batchPrepayDAO.load(number,companyid);
	}
	
	@Override
	public T_Batch_Client loadClient(String ci_code,Integer companyid) {
		return clientDAO.loadClient(ci_code, companyid);
	}
	
	@Override
	public T_Money_Bank loadBank(String ba_code,Integer companyid) {
		return bankDAO.queryByCode(ba_code, companyid);
	}
	
	@Override
	@Transactional
	public void save(T_Batch_Prepay prepay, T_Sys_User user) {
		if(prepay == null){
			throw new IllegalArgumentException("参数不能为null");
		}
		if(StringUtil.isEmpty(prepay.getPp_client_code())){
			throw new IllegalArgumentException("批发客户不能为空");
		}
		if(StringUtil.isEmpty(prepay.getPp_ba_code())){
			throw new IllegalArgumentException("银行账户不能为空");
		}
		if(StringUtil.isEmpty(prepay.getPp_manager())){
			throw new IllegalArgumentException("经办人不能为空");
		}
		if (prepay.getPp_money() == null || prepay.getPp_money().doubleValue() == 0d) {
			throw new IllegalArgumentException("预收金额不能为0");
		}
		if (prepay.getPp_money() > 0) {
			prepay.setPp_type(0);
		}else {
			prepay.setPp_type(1);
		}
		prepay.setCompanyid(user.getCompanyid());
		prepay.setPp_us_id(user.getUs_id());
		prepay.setPp_maker(user.getUs_name());
		prepay.setPp_ar_state(CommonUtil.AR_STATE_NOTAPPROVE);
		prepay.setPp_sysdate(DateUtil.getCurrentTime());
		batchPrepayDAO.save(prepay);
	}
	
	@Override
	@Transactional
	public void update(T_Batch_Prepay prepay, T_Sys_User user) {
		if(prepay == null){
			throw new IllegalArgumentException("参数不能为null");
		}
		if(StringUtil.isEmpty(prepay.getPp_client_code())){
			throw new IllegalArgumentException("批发客户不能为空");
		}
		if(StringUtil.isEmpty(prepay.getPp_ba_code())){
			throw new IllegalArgumentException("银行账户不能为空");
		}
		if(StringUtil.isEmpty(prepay.getPp_manager())){
			throw new IllegalArgumentException("经办人不能为空");
		}
		if (prepay.getPp_money() == null || prepay.getPp_money().doubleValue() == 0d) {
			throw new IllegalArgumentException("预收金额不能为0");
		}
		T_Batch_Prepay oldPrepay = batchPrepayDAO.check(prepay.getPp_number(), user.getCompanyid());
		if(oldPrepay == null || !CommonUtil.AR_STATE_FAIL.equals(oldPrepay.getPp_ar_state())){
			throw new RuntimeException("单据已修改，请勿重复提交");
		}
		if (prepay.getPp_money() > 0) {
			prepay.setPp_type(0);
		}else {
			prepay.setPp_type(1);
		}
		prepay.setCompanyid(user.getCompanyid());
		prepay.setPp_us_id(user.getUs_id());
		prepay.setPp_maker(user.getUs_name());
		prepay.setPp_ar_state(CommonUtil.AR_STATE_NOTAPPROVE);
		prepay.setPp_ar_date(null);
		prepay.setPp_sysdate(DateUtil.getCurrentTime());
		batchPrepayDAO.update(prepay);
	}
	
	@Override
	@Transactional
	public T_Batch_Prepay approve(String number, T_Approve_Record record, T_Sys_User user) {
		if (number == null) {
			throw new IllegalArgumentException("参数number不能为null");
		}
		T_Batch_Prepay prepay = batchPrepayDAO.check(number, user.getCompanyid());
		if(prepay == null){
			throw new RuntimeException("单据不存在");
		}
		if(!CommonUtil.AR_STATE_NOTAPPROVE.equals(prepay.getPp_ar_state())){
			throw new RuntimeException("单据已经审核");
		}
		T_Batch_Client client = clientDAO.loadClient(prepay.getPp_client_code(), user.getCompanyid());
		client.setCi_prepay(client.getCi_prepay() + prepay.getPp_money());
		if (CommonUtil.AR_STATE_APPROVED.equals(record.getAr_state())
				&& prepay.getPp_money() < 0 && client.getCi_prepay() < 0) {// 退款则验证客户预收款余额是否足够
			throw new RuntimeException("客户预收款余额不足");
		}
		//更新单据审核状态
		prepay.setPp_ar_state(record.getAr_state());
		prepay.setPp_ar_date(DateUtil.getCurrentTime());
		batchPrepayDAO.updateApprove(prepay);
		//保存审核记录表
		record.setAr_number(number);
		record.setAr_sysdate(DateUtil.getCurrentTime());
		record.setAr_us_name(user.getUs_name());
		record.setAr_type("t_batch_prepay");
		record.setCompanyid(user.getCompanyid());
		approveRecordDAO.save(record);
		if(!CommonUtil.AR_STATE_APPROVED.equals(prepay.getPp_ar_state())){//审核不通过，则直接返回
			return prepay;
		}
		//3.审核通过
		//更新批发客户财务&生成往来明细账
		clientDAO.updatePrepay(client);
		T_Batch_Dealings dealings = new T_Batch_Dealings();
		dealings.setDl_client_code(prepay.getPp_client_code());
		dealings.setDl_number(prepay.getPp_number());
		if(prepay.getPp_money()>0){
			dealings.setDl_type(CommonUtil.BATCHDEALINGS_TYPE_YSK);
		}else {
			dealings.setDl_type(CommonUtil.BATCHDEALINGS_TYPE_YSTK);
		}
		dealings.setDl_discount_money(0d);
		dealings.setDl_receivable(0d);
		dealings.setDl_received(prepay.getPp_money());
		dealings.setDl_debt(client.getCi_receivable()-client.getCi_received()-client.getCi_prepay());
		dealings.setDl_date(DateUtil.getCurrentTime());
		dealings.setDl_manager(user.getUs_name());
		dealings.setDl_remark(prepay.getPp_remark());
		dealings.setDl_sysdate(DateUtil.getCurrentTime());
		dealings.setCompanyid(user.getCompanyid());
		batchDealingsDAO.save(dealings);
		//银行账目及流水
		T_Money_Bank bank = bankDAO.queryByCode(prepay.getPp_ba_code(), user.getCompanyid());
		if(bank != null){
			bank.setBa_balance(bank.getBa_balance()+prepay.getPp_money());
			bankDAO.updateBalanceById(bank);
			T_Money_BankRun bankRun = new T_Money_BankRun();
			bankRun.setBr_ba_code(prepay.getPp_ba_code());
			bankRun.setBr_balance(bank.getBa_balance());
			bankRun.setBr_bt_code(CommonUtil.BANKRUN_BATCHPREPAY);
			bankRun.setBr_date(prepay.getPp_date());
			if(prepay.getPp_money()>0){
				bankRun.setBr_enter(Math.abs(prepay.getPp_money()));
			}else {
				bankRun.setBr_out(Math.abs(prepay.getPp_money()));
			}
			bankRun.setBr_manager(prepay.getPp_manager());
			bankRun.setBr_number(prepay.getPp_number());
			bankRun.setBr_remark(prepay.getPp_remark());
			bankRun.setBr_shop_code(bank.getBa_shop_code());
			bankRun.setBr_sysdate(DateUtil.getCurrentTime());
			bankRun.setCompanyid(user.getCompanyid());
			bankRunDAO.save(bankRun);
		}
		return prepay;
	}
	
	@Override
	@Transactional
	public T_Batch_Prepay reverse(String number, T_Sys_User user) {
		if (number == null) {
			throw new IllegalArgumentException("参数number不能为null");
		}
		T_Batch_Prepay prepay = batchPrepayDAO.check(number, user.getCompanyid());
		if(prepay == null){
			throw new RuntimeException("单据不存在");
		}
		if(!CommonUtil.AR_STATE_APPROVED.equals(prepay.getPp_ar_state())){
			throw new RuntimeException("单据未审核或审核未通过");
		}
		T_Batch_Client client = clientDAO.loadClient(prepay.getPp_client_code(), user.getCompanyid());
		client.setCi_prepay(client.getCi_prepay() - prepay.getPp_money());
		if (prepay.getPp_money() > 0 && client.getCi_prepay() < 0) {// 收款则验证客户预收款余额是否足够
			throw new RuntimeException("客户预收款余额不足");
		}
		//更新单据审核状态
		prepay.setPp_ar_state(CommonUtil.AR_STATE_NOTAPPROVE);
		prepay.setPp_ar_date(DateUtil.getCurrentTime());
		batchPrepayDAO.updateApprove(prepay);
		//保存审核记录表
		T_Approve_Record record = new T_Approve_Record();
		record.setAr_state(CommonUtil.AR_STATE_REVERSE_APPROVE);
		record.setAr_describe(user.getUs_name()+"反审核单据");
		record.setAr_number(number);
		record.setAr_sysdate(DateUtil.getCurrentTime());
		record.setAr_us_name(user.getUs_name());
		record.setAr_type("t_batch_prepay");
		record.setCompanyid(user.getCompanyid());
		approveRecordDAO.save(record);
		//更新批发客户财务&删除往来明细账
		clientDAO.updatePrepay(client);
		T_Batch_Dealings dealings = new T_Batch_Dealings();
		dealings.setDl_client_code(prepay.getPp_client_code());
		dealings.setDl_number(prepay.getPp_number());
		if(prepay.getPp_money()>0){
			dealings.setDl_type(CommonUtil.BATCHDEALINGS_TYPE_YSK);
		}else {
			dealings.setDl_type(CommonUtil.BATCHDEALINGS_TYPE_YSTK);
		}
		dealings.setDl_discount_money(0d);
		dealings.setDl_receivable(0d);
		dealings.setDl_received(-prepay.getPp_money());
		dealings.setDl_debt(client.getCi_receivable()-client.getCi_received()-client.getCi_prepay());
		dealings.setDl_date(DateUtil.getCurrentTime());
		dealings.setDl_manager(user.getUs_name());
		dealings.setDl_remark("反审核恢复账目往来明细");
		dealings.setDl_sysdate(DateUtil.getCurrentTime());
		dealings.setCompanyid(user.getCompanyid());
		batchDealingsDAO.save(dealings);
		//银行账目及流水
		T_Money_Bank bank = bankDAO.queryByCode(prepay.getPp_ba_code(), user.getCompanyid());
		if(bank != null){
			bank.setBa_balance(bank.getBa_balance() - prepay.getPp_money());
			bankDAO.updateBalanceById(bank);
			T_Money_BankRun bankRun = new T_Money_BankRun();
			bankRun.setBr_ba_code(prepay.getPp_ba_code());
			bankRun.setBr_balance(bank.getBa_balance());
			bankRun.setBr_bt_code(CommonUtil.BANKRUN_BATCHPREPAY);
			bankRun.setBr_date(prepay.getPp_date());
			if(prepay.getPp_money()>0){
				bankRun.setBr_out(Math.abs(prepay.getPp_money()));
			}else {
				bankRun.setBr_enter(Math.abs(prepay.getPp_money()));
			}
			bankRun.setBr_manager(user.getUs_name());
			bankRun.setBr_number(prepay.getPp_number());
			bankRun.setBr_remark("反审核恢复账目");
			bankRun.setBr_shop_code(bank.getBa_shop_code());
			bankRun.setBr_sysdate(DateUtil.getCurrentTime());
			bankRun.setCompanyid(user.getCompanyid());
			bankRunDAO.save(bankRun);
		}
		return prepay;
	}
	
	@Override
	@Transactional
	public void del(String number, Integer companyid) {
		T_Batch_Prepay prepay = batchPrepayDAO.check(number, companyid);
		if(prepay == null){
			throw new RuntimeException("单据不存在");
		}
		if(!CommonUtil.AR_STATE_NOTAPPROVE.equals(prepay.getPp_ar_state()) && !CommonUtil.AR_STATE_FAIL.equals(prepay.getPp_ar_state())){
			throw new RuntimeException("单据已审核通过不能删除！");
		}
		batchPrepayDAO.del(number, companyid);
	}
	
}
